package com.oncliedisk.administrator.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.content.OnlineConfig;
import com.oncliedisk.administrator.model.FileTaskModel;
import com.oncliedisk.administrator.model.LocalFileDirInfo;
import com.oncliedisk.administrator.onlinedisk.R;
import com.oncliedisk.administrator.utils.ExploerLoadSdFileTask;
import com.oncliedisk.administrator.utils.HttpUtils;
import com.oncliedisk.administrator.utils.ImageUtils;
import com.ypy.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.Stack;

/**
 * Created by Administrator on 2015/12/17 0017.
 */
public class UploadOthersActivity extends Activity implements
        View.OnClickListener {
    public ListView listView;
    protected LinearLayout ll_loading;

    private ViewHolder holder;
    public FileExploerAdapter exploerAdapter;
    public File curFile;
    private ImageView iv_back;
    public File root;
    private String FILE_DES_DIR= "/";
    protected Button btn_upload;
    protected Button bt_selectall;
    protected TextView select_folder;

    /**
     * 是否是在选择文件状态
     */
    private boolean mSelected;
    /**
     * 点击勾选的条目
     */
    public ArrayList<LocalFileDirInfo> selectedData = new ArrayList<LocalFileDirInfo>();
    /**
     * 当前目录下所有文件，包括文件夹+文件
     */
    public ArrayList<LocalFileDirInfo> list;
    /**
     * 当前目录下文件，不包括文件夹
     */
    public ArrayList<LocalFileDirInfo> mFileData;

    /**
     * 历史点击item的位置
     */
    private Stack<Integer> history = new Stack<Integer>();
    /**
     * 历史目录
     */
    private Stack<Recorder> mStack = new Stack<Recorder>();


    private class Recorder {
        /* 当前文件夹名 */
        @SuppressWarnings("unused")
        String dirPath = "";
        /* 当前文件夹下的LIST */
        ArrayList<LocalFileDirInfo> list;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_uploadmedia);
        if (!ExploerLoadSdFileTask.isMountSdCard(this)) {
            ExploerLoadSdFileTask.showToast(this, "请插入SD卡",
                    Toast.LENGTH_SHORT);
            return;
        }
        initView();
        initListener();
        history.clear();
        history.push(0);
        initStackInfo();
        root = Environment.getExternalStorageDirectory();
        curFile = root;
        fillData();
        Intent intent = getIntent();
        String mDesPath = intent.getStringExtra("desPath");
        if(mDesPath != null) {
            FILE_DES_DIR = mDesPath;
            select_folder.setText("我的网盘"+FILE_DES_DIR);
        }


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                LocalFileDirInfo info = list.get(position);
                if (!info.isFile) {
                    initCurrentFolderState();
                    history.push(0);
                    list.clear();
                    refresh();
                    curFile = info.file;
                    Recorder r = new Recorder();
                    r.dirPath = curFile.getPath();
                    mStack.push(r);
                    fillData();

                } else {
                    // is file
                    holder = (ViewHolder) view.getTag();
                    holder.ch_upload.toggle();
                    info.isSelected = true;
                    exploerAdapter.isSelected.put(position, holder.ch_upload.isChecked());

                    if (holder.ch_upload.isChecked()) {
                        selectedData.add(list.get(position));
                    } else {
                        info.isSelected = false;
                        selectedData.remove(list.get(position));
//                        if (selectedData.size() == 0) {
//                            UploadManager.getInstance(
//                                    UploadFileExploerActivity.this)
//                                    .clearUploadQueue();
//                        }
                    }

                    changeButtonState();
                    if (!selectedData.isEmpty()) {
                        mSelected = true;
                    } else {
                        mSelected = false;
                    }
                }
            }
        });
    }

    private void initListener() {
        btn_upload.setOnClickListener(this);
        bt_selectall.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    private void initView() {
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        listView = (ListView)findViewById(R.id.listview);
        btn_upload = (Button)findViewById(R.id.btn_upload);
        bt_selectall = (Button)findViewById(R.id.bt_selectall);
        iv_back = (ImageView)findViewById(R.id.iv_back);
        select_folder = (TextView) findViewById(R.id.select_folder);

    }

    private void changeButtonState() {
        if (!selectedData.isEmpty()) {
            btn_upload.setText("上传" + "("
                    + selectedData.size() + ")");
            bt_selectall.setText("取消");
            btn_upload.setEnabled(true);
            btn_upload.setFocusable(true);
            btn_upload.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_upload_pressed));

        } else {
            btn_upload.setText("上传(0)");
            bt_selectall.setText("全选");
            btn_upload.setEnabled(false);
            btn_upload.setFocusable(false);
            btn_upload.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_upload_default));

        }
    }

    private void initCurrentFolderState() {
        if (!selectedData.isEmpty()) {
            selectedData.clear();
        }
        mSelected = false;
        btn_upload.setText("上传（0）");
        bt_selectall.setText("全选");
        btn_upload.setEnabled(false);
        btn_upload.setFocusable(false);
        btn_upload.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_upload_default));
    }
    private void refresh() {
        exploerAdapter.notifyDataSetChanged();
        int curPos;
        try {
            curPos = history.lastElement();
            if (curPos < 0 || curPos > listView.getBottom()) {
                history.set(history.size() - 1, 0);
            }
            listView.setSelection(history.lastElement());
        } catch (NoSuchElementException e) {
            e.printStackTrace();
        }
    }
    public void fillData() {
        //加载数据，进度条可见
        ll_loading.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                list = ExploerLoadSdFileTask.loadSdFile(curFile);
                if(null == list || list.size() == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //没有数据加载，进度条不可见
                            ll_loading.setVisibility(View.INVISIBLE);
                            Toast.makeText(UploadOthersActivity.this, "没有扫描到视频文件!", Toast.LENGTH_LONG).show() ;
                        }
                    });
                    return ;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //数据加载完毕，进度条不可见
                        ll_loading.setVisibility(View.INVISIBLE);
                        if(exploerAdapter == null) {
                            exploerAdapter = new FileExploerAdapter(UploadOthersActivity.this);
                            listView.setItemsCanFocus(false);
                            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                            listView.setAdapter(exploerAdapter);

                        }else {
                            exploerAdapter.notifyDataSetChanged();
                        }
                        exploerAdapter.init();
                        mStack.lastElement().list = new ArrayList<LocalFileDirInfo>(
                                list);
                        refresh();
                    }
                });
            }
        }).start();
    }
    class FileExploerAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        /**
         * 当前目录下文件选择状态
         */
        private HashMap<Integer, Boolean> isSelected;

        public FileExploerAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
        }

        public void init() {
            mFileData = new ArrayList<LocalFileDirInfo>();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                if (list.get(i).isFile) {
                    mFileData.add(list.get(i));
                }
            }
            isSelected = new HashMap<Integer, Boolean>();
            int mSize = mFileData.size();
            for (int i = 0; i < mSize; i++) {
                isSelected.put(i, false);
            }
        }

        @Override
        public int getCount() {
            if (list == null || list.size() == 0) {
                return 0;
            } else {
                return list.size();
            }
        }

        // 当前目录下文件数，不包括文件夹
        public int getFileCount() {
            if (mFileData == null || mFileData.size() == 0) {
                return 0;
            } else {
                return mFileData.size();
            }
        }

        @Override
        public LocalFileDirInfo getItem(int position) {
            return list.get(position);
        }

        public LocalFileDirInfo getFileItem(int position) {
            return mFileData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {

                convertView = mInflater.inflate(
                        R.layout.file_exploer_list_item, null);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.file_icon);
                holder.text = (TextView) convertView
                        .findViewById(R.id.fileDirName);
                holder.textSize = (TextView) convertView
                        .findViewById(R.id.fileSize);
                holder.modifyText = (TextView) convertView
                        .findViewById(R.id.lastModifyTime);
                holder.btn_enter = (Button) convertView
                        .findViewById(R.id.enterBtn);
                holder.ch_upload = (CheckBox) convertView
                        .findViewById(R.id.uploadCheckBox);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.ch_upload.setChecked(list.get(position).isSelected);
            holder.update(UploadOthersActivity.this, list.get(position));
            return convertView;
        }
    }
    private class ViewHolder {

        public ImageView image;
        public TextView text;
        private TextView textSize;
        public TextView modifyText;
        public Button btn_enter;
        public CheckBox ch_upload;
        public String size;

        public void update(Context ctx, final LocalFileDirInfo info) {
            text.setText(info.name);
            btn_enter.setVisibility(View.GONE);
            ch_upload.setVisibility(View.GONE);
            if (info.isFile) {

                image.setImageResource(ImageUtils.getImageByType(info.getName()));

                size = info.filesize;
                ch_upload.setVisibility(View.VISIBLE);
            } else {
                btn_enter.setVisibility(View.VISIBLE);
                image.setImageResource(R.drawable.directory_icon);
                size = String.format("%s个文件",
                        info.fileNum);
            }
            textSize.setText(size);
            modifyText.setText(info.ctime);
        }
    }

    @Override
    protected void onDestroy() {
        if (selectedData != null && !selectedData.isEmpty()) {
            selectedData.clear();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_selectall://全选
                changeSelectedFile();
                changeButtonState();
                break;

            case R.id.btn_upload://上传操作
//                Toast.makeText(this,"点击了上传",Toast.LENGTH_SHORT).show();
                if(!HttpUtils.isNetworkAvailable(UploadOthersActivity.this)){
                    Toast.makeText(UploadOthersActivity.this, "请检查网络状态是否可用!", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (LocalFileDirInfo model : selectedData) {
                    Log.i("info", "执行插入");
                    FileTaskModel taskModel = new FileTaskModel();
                    taskModel.setFileName(model.getName());
                    taskModel.setPath(FILE_DES_DIR);
                    taskModel.setLocalPath(model.getFile().getAbsolutePath());
//                    taskModel.setType(model.getMimeType());
                    taskModel.setState(FileTaskModel.STATE_WAIT_DOWN);
                    taskModel.setTaskType(OnlineConfig.TYPE_UP);
//                    String path = model.getPath();
//                    File file = new File(path);
                    taskModel.setSize(ExploerLoadSdFileTask.formateFileSize(model.getFile().length()));
                    Dao.getInstance(UploadOthersActivity.this).saveFileTask(taskModel);
                }
                //存储完成，执行提醒传输页面.
                Toast.makeText(UploadOthersActivity.this, "已加入上传列表", Toast.LENGTH_SHORT).show();
                EventBus.getDefault().post(new String(OnlineConfig.TYPE_UP));
                break;

            case R.id.iv_back:
               finish();
                break;
            default:
                break;
        }
    }
    private void changeSelectedFile() {
        if (!selectedData.isEmpty()) {
            selectedData.clear();
        }
        if (!mSelected) {
            mSelected = true;
            if (exploerAdapter != null) {
                for (int i = 0; i < exploerAdapter.getFileCount(); i++) {
                    this.exploerAdapter.getFileItem(i).isSelected = true;
                    selectedData.add(mFileData.get(i));
                }
                this.exploerAdapter.notifyDataSetChanged();
            }
        } else {
            mSelected = false;
            if (exploerAdapter != null) {
                for (int i = 0; i < exploerAdapter.getFileCount(); i++) {
                    this.exploerAdapter.getFileItem(i).isSelected = false;
                    selectedData.remove(mFileData.get(i));
                }
                this.exploerAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (!ExploerLoadSdFileTask.isMountSdCard(this)) {
                finish();
                return true;
            }

            initCurrentFolderState();

            if (history.size() > 0)
                history.pop();
            if (isRootDirectory(curFile)) {
                finish();
//                list.clear();
                return true;
            } else {
				/*
				 * curFile = curFile.getParentFile(); afterServiceConnected();
				 */
                mStack.pop();
                curFile = curFile.getParentFile();
                list.clear();
                list.addAll(mStack.lastElement().list);
                if (exploerAdapter != null) {
                    exploerAdapter.init();
                    for (int i = 0; i < exploerAdapter.getFileCount(); i++) {
                        this.exploerAdapter.getFileItem(i).isSelected = false;
                        selectedData.remove(mFileData.get(i));
                    }
                }
                refresh();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private boolean isRootDirectory(File f) {
        if (f.getPath().equals(root.getPath()))
            return true;
        return false;
    }
    private void initStackInfo() {
        Recorder r = new Recorder();
        r.dirPath = Environment.getExternalStorageDirectory().getPath();
        r.list = new ArrayList<LocalFileDirInfo>();
        mStack.push(r);
    }
}
